<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/29 14:47
 * Modified Time: 2019/6/29 14:47
 * Version: 2.0
 */

namespace App\Modules\Activity\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class ActivityCriteria extends BaseCriterias
{
    private $store_id;
    private $be_overdue;

    public function __construct($store_id,$be_overdue=0)
    {
        $this->store_id = $store_id;
        $this->be_overdue = $be_overdue;
    }

    /*
     * 获取店铺公告列表
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $store_id = $this->store_id;
        $be_overdue = $this->be_overdue;


        $select = [
            'hx_store_activity.id',
            'store_id',
            'title',
            'content',
            'playbill',
            'from_unixtime(expire, "%Y-%m-%d %H:%i:%S") as expire',
            'expire-UNIX_TIMESTAMP(now()) as second',
            'if(expire>UNIX_TIMESTAMP(now()),0,1) as is_expired',
            'hx_store_activity.created_at'
        ];

        $select = implode($select,',');
        $model = $model->selectRaw($select)->where('store_id',$store_id)
            ->with(['picture'=>function($query){
                $query->select('id','image');
            }])
            ->when($be_overdue,function ($query){
                $query->whereRaw('expire>UNIX_TIMESTAMP(now())');
            })
            ->orderBy('id', 'DESC');

        return $model;
    }
}